﻿using System;
using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;

namespace CodeCounsel.SharePoint.RibbonDesigner.Model
{
    public class DomainElementCollection
        : ObservableCollection<DomainElement>
    { 
        public DomainElement Owner { get; private set; }

        public DomainElementCollection(DomainElement owner)
        {
            Owner = owner;
        }

        public DomainElementCollection(DomainElement owner, IEnumerable<DomainElement> items)
            : base(items)
        {
            Owner = owner;
            foreach (DomainElement element in base.Items)
            {
                element.SetParent(owner);
            }
        }

        protected override void InsertItem(int index, DomainElement item)
        {
            base.InsertItem(index, item);
            item.SetParent(Owner);
        }

        protected override void SetItem(int index, DomainElement item)
        {
            DomainElement currentItem = this[index];
            if (currentItem != null)
            {
                currentItem.SetParent(null);
            }
            base.SetItem(index, item);
            item.SetParent(Owner);
        }

        protected override void RemoveItem(int index)
        {
            DomainElement model = this[index];
            base.RemoveItem(index);
            if (model != null)
            {
                model.SetParent(null);
            }
        }

        protected override void ClearItems()
        {
            List<DomainElement> items = this.ToList();
            base.ClearItems();
            foreach (DomainElement model in items)
            {
                model.SetParent(null);
            }
        }
    }
}